<template>
  <div v-loading="loading">
    <div v-if="isAsync">
      <span class="text-danger">
        此处删除附件请悉知删除后省农担也同步删除，添加需手动点击最下方按钮同步更新至省农担
      </span>
    </div>
    <h4 class="attach-title mt-1">
      <div class="d-flex justify-content-between align-items-center">
        <div>调查附件</div>
        <div>
          <el-button type="text" @click="showAttach = !showAttach">
            <i :class="`fa fa-sort-${showAttach ? 'asc' : 'desc'}`"></i>
          </el-button>
        </div>
      </div>
    </h4>
    <hr />
    <div v-show="showAttach">
      <attach-scene
        :project-data="projectData"
        :view-mode="isView"
        @after-data="handleSceneAfterData"
        @success="handleSceneSuccess"
      ></attach-scene>
    </div>
    <h4 class="attach-title mt-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>调查资料</div>
        <div>
          <el-button type="text" @click="showUploadAttach = !showUploadAttach">
            <i :class="`fa fa-sort-${showUploadAttach ? 'asc' : 'desc'}`"></i>
          </el-button>
        </div>
      </div>
    </h4>
    <hr />
    <div v-show="showUploadAttach">
      <attach-upload
        :tags="uploadTags"
        :batch-no="relatedId"
        :view-mode="isView"
        v-bind="$listeners"
        ref="upload"
        @after-data="handleAfterData"
      ></attach-upload>
    </div>

    <div v-if="isAsync">
      <attach-risk-main :related-id="relatedId" :view-mode="isView"></attach-risk-main>
    </div>

    <div class="text-center mt-5" v-if="isAsync">
      <el-button
        type="primary"
        class="btn-long"
        @click="changeAttachStatus"
        :loading="submitLoading"
      >
        同步更新省农担附件
      </el-button>
      <div class="mt-5 text-warning">
        请先告知省农担审批人员附件变动后再操作，放款审批开始后不能再修改附件。
      </div>
    </div>
  </div>
</template>

<script>
import {
  enumPersonalTags,
  enumCompanyTags,
  hasAttachFinish,
  hasSceneMediaFinish,
  hasSceneImageFinish,
  hasSceneReportFinish,
} from '@/credit/views/city/bus/normal/invest/attach'

import AttachUpload from '@/bank/components/attach/Upload'
import AttachScene from '@/credit/views/city/bus/normal/invest/AttachScene'
import { mapGetters } from 'vuex'
import AttachRiskMain from '@/credit/views/county/unionProvince/components/projectApprove/components/risk/AttachMain'

export default {
  components: {
    AttachUpload,
    AttachScene,
    AttachRiskMain,
  },
  props: {
    viewMode: Boolean,
    relatedId: String,
    isAsync: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      projectData: {},
      signData: {},
      attachs: [],
      showAttach: true,
      showUploadAttach: true,
      submitLoading: false,
      solidData: {},
    }
  },
  computed: {
    ...mapGetters(['entrustContract']),
    isCompany() {
      return +this.projectData.customer_type === 1
    },
    uploadTags() {
      return this.isCompany ? enumCompanyTags : enumPersonalTags
    },
    isView() {
      return this.viewMode
    },
    attachStatus() {
      return +this.projectData.invest_datum_status
    },
    dataId() {
      return this.solidData.id
    },
  },
  watch: {
    relatedId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async changeAttachStatus() {
      this.submitLoading = true
      if (this.dataId) {
        await this.$api.updateData(this.$serviceName, 'project_approval_register', this.dataId, {
          gua_method_des: this.entrustContract.gua_method_des || this.solidData.gua_method_des,
          res_funds: this.entrustContract.reply_funds || this.solidData.res_funds,
          res_months: this.entrustContract.load_years || this.solidData.res_months,
          funds_use_dir: this.entrustContract.funds_use_dir || this.solidData.funds_use_dir,
        })
      }
      this.$api
        .updateData(this.$serviceName, 'customer_related', this.relatedId, {
          is_supply_datum: 1,
        })
        .then(() => {
          this.$message.success('同步成功，请勿多次点击同步，无效请联系管理员！')
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description ?? '同步失败！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    async getData() {
      if (!this.relatedId || this.loading) return Promise.resolve()
      this.loading = true
      if (this.isAsync) {
        await this.$store.dispatch('getEntrustContract', this.relatedId)
        await this.$api
          .getData({
            table: 'project_approval_register',
            params: {
              'customer_related_id.eq': this.relatedId,
              'approval_register_type.eq': 1,
            },
          })
          .then(res => {
            this.solidData = res?.data?.[0] ?? {}
          })
      }

      return Promise.all([this.getRelatedData()]).finally(() => {
        this.loading = false
      })
    },
    getRelatedData() {
      if (this.$refs.upload) {
        this.$nextTick(() => {
          this.$refs.upload.init()
        })
      }
      return this.$api
        .getData({
          table: 'customer_related',
          params: {
            'customer_related_id.eq': this.relatedId,
          },
        })
        .then(res => {
          this.projectData = res?.data?.[0] ?? {}
          this.$emit('status', this.attachStatus)
          this.$emit('getData', this.projectData)
        })
    },

    handleAfterData({ list, emit }) {
      if (emit) {
        this.$emit('success', list)
      }
      this.attachs = list
      if (this.isView || !this.emit) return
      this.updateStatus()
    },

    handleSignTypeChange() {
      this.getData().then(() => this.updateStatus())
    },

    // 更新项目附件状态
    updateStatus() {
      // 判断附件状态
      const isAttachUpload = hasAttachFinish(this.attachs, this.projectData)

      // 现场音视频
      const isMediaUpload = hasSceneMediaFinish(this.attachs, this.projectData).finish

      // 调查图片
      const isImageUpload = hasSceneImageFinish(this.attachs, this.projectData).finish

      // 尽调报告
      const isReportUpload = hasSceneReportFinish(this.projectData).finish
      const isAllUpload = isAttachUpload && isMediaUpload && isImageUpload && isReportUpload
      const currentStatus = isAllUpload ? 1 : 0
      if (this.attachStatus === currentStatus) return
      this.updateAttachStatus(currentStatus)
    },

    // 更新状态
    updateAttachStatus(status) {
      this.$api
        .updateData({
          table: 'customer_related',
          id: this.relatedId,
          data: {
            invest_datum_status: status,
          },
        })
        .then(res => {
          this.getData()
          this.$emit('success', res)
          this.$emit('status', status)
        })
        .catch(err => {
          this.$message({
            showClose: true,
            message: err?.data?.error_description || '附件状态更新失败',
            type: 'warning',
            duration: 0,
          })
        })
    },

    handleSceneAfterData({ list, emit }) {
      this.attachs = list
      if (emit) {
        this.$emit('success', list)
      }
      if (this.isView || !emit) return
      this.updateStatus()
    },
    handleSceneSuccess(res) {
      this.getData().finally(() => {
        this.updateStatus()
      })
      this.$emit('success', res)
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
